package com.ruyuan2020.furnishing.common.config;

import com.ruyuan2020.common.domain.JsonResult;
import com.ruyuan2020.common.exception.BusinessException;
import com.ruyuan2020.common.exception.NotFoundException;
import com.ruyuan2020.common.util.ResultHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionConfig {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionConfig.class);

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public JsonResult<?> handleBusinessException(BusinessException e) {
        return ResultHelper.fail(String.valueOf(HttpStatus.BAD_REQUEST.value()), e.getMessage());
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public JsonResult<?> handleNotFoundException(NotFoundException e) {
        return ResultHelper.fail(String.valueOf(HttpStatus.NOT_FOUND.value()), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    public JsonResult<?> handleAllException(Throwable e) {
        log.error(e.getMessage(), e);
        return ResultHelper.fail(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), e.getMessage());
    }
}
